using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using Microsoft.MediaCenter.UI;
using Microsoft.MediaCenter.Hosting;
using Level65.WMVHelper;
using Level65.ClipShow;
using System.Threading;

namespace ClipShow
{
    public class MediaBrowseCodeBehind : CoreUICodeBehind 
    {
        private Thread _thread;
        private ArrayList _thumbFlips = new ArrayList();
        private int _thumbFlipIndex;
        private Choice _myChosenContentItems;
        private bool _firstItemIn = true;
        private Command _changedPlaylist;
        private bool _showVideoSources = true;
        private bool _linkedPlaylistMode;
        private string _parentTitle = "";
        private bool _finishedCrawl = false;

        public MediaBrowseCodeBehind()
        {
            _myChosenContentItems = new Choice();
            base.BuildLibraryOptions(true, true);
            BuildCommandBar(_showVideoSources);
            BuildFilterBar();
        }
        //public MediaBrowseCodeBehind(MediaMetaData parent)
        //{
        //    // Stop current playback
        //    base.StopPlayback(false);

        //    base.BuildLibraryOptions(false, true);
        //    _myChosenContentItems = new Choice();
        //    if (!BuildVideoChildren(parent, false, true))
        //    {
        //        // We found no linked videos, so place itself in the list to prevent screen crash
        //        MediaListItem mli = new MediaListItem();
        //        mli.SourceItem = parent;
        //        base.VideoMetaDataList.Add(mli);
        //    }

        //    try
        //    {
        //        _showVideoSources = false;
        //        BuildCommandBar(_showVideoSources);
        //        BuildFilterBar();
        //        _firstItemIn = false;
        //        ArrayListDataSet temp = new ArrayListDataSet();
        //        temp.Add(parent);
        //        _myChosenContentItems.Options = temp;
                
        //        _parentTitle = String.Format("Linked media to '{0}'", parent.Title);
        //        base.CurrentView = TileViewType.SingleMediaItem;
        //        this.LinkedPlaylistMode = true;
        //    }
        //    catch (SystemException se)
        //    {
        //        base.ShowDialog("clipShow Exception", se.Message, true);
        //    }
        //}

        public void StartUp()
        {
            base.StopPlayback(false);
            Storage st = new Storage();
            // First purge "dated" catalogs 
            st.PurgeCatalog();
            Application.DeferredInvokeOnWorkerThread(new DeferredHandler(CrawlForMedia),
                new DeferredHandler(PrepCrawlForRemote), base.AppSettings.IndexRecordedTv);
            
        }
        protected void CrawlForMedia(object args)
        {
            Storage st = new Storage();
            // First purge "dated" catalogs 
            st.PurgeCatalog();

            bool indexRecordedTv = (bool)args;

            StartupCodeBehind scb = new StartupCodeBehind();
            
            // First look for local non-tv media
            scb.SearchLocal("my media", base.AppSettings.MediaTypes);

            if (indexRecordedTv)
            {
                // Now search for my TV
                scb.SearchLocal("my recorded tv", base.AppSettings.RecordedTvTypes);
            }
        }

        protected void CrawlForRemoteMedia(object args)
        {
            StartupCodeBehind scb = new StartupCodeBehind();
            scb.CrawlLinkedShares();
        }

        protected void BuildThumbnails(object args)
        {
            // Check for newly added libraries
            Storage st = new Storage();
            bool aNewItem = (bool)args;

            foreach (ClipShowContent cms in st.GetMediaLibraries())
            {
                bool foundItem = false;
                foreach (FilterBarItem fbi in MediaFilters.Options)
                {
                    if (cms.ContentSourceName.Equals(fbi.FilterName))
                    {
                        foundItem = true;
                        break;
                    }
                }
                if (!foundItem)
                {
                    FilterBarItem fbi = new FilterBarItem(cms.ContentSourceName, 
                        String.Format("view media in {0}", cms.ContentSourceName), TileViewType.SingleMediaItem);
                    MediaFilters.Options.Add(fbi);
                    aNewItem = true;
                }
            }

            if (aNewItem)
            {
                // Refresh the library with the new items
                base.BuildLibraryOptions(true, true);
            }

            // Check  and process thumbnail work
            _thread = new Thread(new ThreadStart(StartThumbnailBuild));
            _thread.Name = "vmc_clipShow_ThumbBuildThread";
            _thread.IsBackground = true;
            _thread.Priority = ThreadPriority.Normal;
            _thread.Start();
        }

        protected void PrepCrawlForRemote(object args)
        {
            _finishedCrawl = true;

            bool aNewItem = false;
            // Check for newly added libraries
            Storage st = new Storage();
            foreach (ClipShowContent cms in st.GetMediaLibraries())
            {
                bool foundItem = false;
                foreach (FilterBarItem fbi in MediaFilters.Options)
                {
                    if (cms.ContentSourceName.Equals(fbi.FilterName))
                    {
                        foundItem = true;
                        break;
                    }
                }
                if (!foundItem)
                {
                    aNewItem = true;
                    if (!cms.ContentSourceName.Equals(MEDIA_LOADING_MSG))
                    {
                        FilterBarItem fbi = new FilterBarItem(cms.ContentSourceName, String.Format("view media in {0}", cms.ContentSourceName),
                            TileViewType.SingleMediaItem);
                        MediaFilters.Options.Add(fbi);
                    }
                }
            }

            if (MediaFilters.Options.Count==1)
            {
                MediaFilters.Options.Add(new FilterBarItem("by date", "view my media items by date", TileViewType.Timeline));
                FilterBarItem fbiFirst = (FilterBarItem)MediaFilters.Options[0];
                fbiFirst.FilterDescription = "view my local media";
                base.BuildMediaByFilter(fbiFirst);
            }

            Application.DeferredInvokeOnWorkerThread(new DeferredHandler(CrawlForRemoteMedia), new DeferredHandler(BuildThumbnails), aNewItem);
        }

        #region Private subroutines
        private const string MEDIA_LOADING_MSG = "my media";
        private void BuildFilterBar()
        {
            // Build filters
            Storage st = new Storage();
            bool hasLibraries = (st.GetMediaLibraryCount() > 0);

            ArrayListDataSet tempFilters = new ArrayListDataSet();

            if (!hasLibraries)
            {
                tempFilters.Add(new FilterBarItem(MEDIA_LOADING_MSG, "searching for media, please wait...", TileViewType.SingleMediaItem));
                base.AddMediaFilterItems(tempFilters);
            }

            foreach (ClipShowContent cms in st.GetMediaLibraries())
            {
                string description = String.Format("view media in {0}", cms.ContentSourceName);
                if (cms.ContentSourceName.Equals("my media"))
                {
                    description = "view my local media";
                }

                tempFilters.Add(new FilterBarItem(cms.ContentSourceName, description, TileViewType.SingleMediaItem));
            }

            // Check for playlists
            if (st.GetMyCollections().Count > 0)
            {
                tempFilters.Add(new FilterBarItem("my playlists", "view my playlists", TileViewType.PlayLists));
            }

            ClipShowContent cm = st.GetSnagCollection();
            if (cm.MediaItems.Count > 0)
            {
                tempFilters.Add(new FilterBarItem("my snags", "view my snagged clips", TileViewType.Snags));
            }

            if (this.TagsExist)
            {
                tempFilters.Add(new FilterBarItem("by tag", "view my media by tags", TileViewType.Topics));
                //Removed 11/3/2008
                //tempFilters.Add(new FilterBarItem("by tag thumbnails", "view my media by tag thumbnails", TileViewType.MediaItems));
            }

            if ( (tempFilters.Count > 0) && (hasLibraries))
            {
                tempFilters.Add(new FilterBarItem("by date", "view my media items by date", TileViewType.Timeline));
            }

            base.AddMediaFilterItems(tempFilters);
        }
        private bool BuildVideoChildren(MediaMetaData sourceItem, bool includeSelfInList, bool includeDirectoryFiles)
        {
            Topics tp = new Topics();
            string firstTerm = tp.BuildSingleTopic(sourceItem);

            ArrayListDataSet sourceVideos = base.PopulateMediaLibrary();
            ArrayListDataSet temp = new ArrayListDataSet();
            ArrayListDataSet tempDF = new ArrayListDataSet();

            if (includeSelfInList)
            {
                MediaListItem mliFirst = new MediaListItem(sourceItem);
                temp.Add(mliFirst);
                tempDF.Add(mliFirst);
            }

            for (int Ctr = 0; Ctr < sourceVideos.Count; Ctr++)
            {
                MediaMetaData source = (MediaMetaData)sourceVideos[Ctr];
                MediaListItem mli = new MediaListItem();
                mli.SourceItem = source;
                if (includeDirectoryFiles)
                {
                    if (Path.GetDirectoryName(sourceItem.Url).Equals(Path.GetDirectoryName(source.Url)))
                    {
                        tempDF.Add(mli);
                    }
                }

                // Fixed on 12/23/2008 
                if (firstTerm.Length > 0)
                {
                    string[] terms = firstTerm.Split(';');
                    foreach (string term in terms)
                    {
                        if (CheckForKeyword(source, term))
                        {
                            if (!source.Url.Equals(sourceItem.Url))
                            {
                                temp.Add(mli);
                            }
                            break;
                        }
                    }
                }
            }
            if (temp.Count > 1)
            {
                foreach(MediaListItem ctr in temp) 
                {
                    base.VideoMetaDataList.Add(ctr);
                }
                return (true);
            }
            else
            {
                if (includeDirectoryFiles)
                {
                    foreach (MediaListItem ctr in tempDF)
                    {
                        base.VideoMetaDataList.Add(ctr);
                    }
                    return (true);
                }
                else
                {
                    return (false);
                }
            }
        }

        private void StartThumbnailBuild()
        {
            try
            {
                Reader wmv = new Reader();
                wmv.BuildThumbnails(base.AppSettings.UseEffects);
            }
            catch 
            {
                // TODO:  Handle exception here
            }
        }

        private void BuildCommandBar(bool ShowVideoResources)
        {
            if (ShowVideoResources)
            {
                ArrayListDataSet tempCommandBarItems = new ArrayListDataSet();
                tempCommandBarItems.Add(new CommandBarItem("Shuffle All", "shuffle and play all my media"));
                tempCommandBarItems.Add(new CommandBarItem("Settings", "view/change configuration settings"));
                tempCommandBarItems.Add(new CommandBarItem("About", "about clipShow"));
                base.AddCommandBarItems(tempCommandBarItems);
            }
            else
            {
                ArrayListDataSet tempCommandBarItems = new ArrayListDataSet();
                tempCommandBarItems.Add(new CommandBarItem("Browse", "Browse my media library"));
                tempCommandBarItems.Add(new CommandBarItem("About", "about clipShow"));
                base.AddCommandBarItems(tempCommandBarItems);
            }
        }
        #endregion

        #region Methods
        public MediaPlayCodeBehind ResultPageWithChannelFromTimeline 
        {
            get
            {
                // First stop the thumbnail thread if it is running
                CleanupThreads();
                PreviewChannelVItem ci = (PreviewChannelVItem)base.TimelineMediaLibraryList[base.CurrentTileIndex];
                MediaPlayCodeBehind cb = new MediaPlayCodeBehind();
                try
                {
                    ClipCollection mc = new ClipCollection();
                    mc.ClipLength = base.AppSettings.DefaultClipLength;
                    mc.Name = ci.SourceItem.Name;
                    mc.Items.Add(ci);

                    int Ctr = 0;
                    foreach (MediaMetaData item in ci.SourceItem.MediaItems)
                    {
                        if (Ctr == 0)
                        {
                            MediaListItem mli = new MediaListItem(item);
                            mli.SourceItem.Thumbnail = new Image(BuildImagePath(mli.SourceItem.ThumbnailUrl));
                            cb.VideoMetaDataList.Add(mli);
                            Ctr = 1;
                        }
                        else
                        {
                            cb.TileItems.Add(item);
                        }
                    }
                    cb.CurrentChannel = mc;

                    if ( (ci.SourceItem.Name.StartsWith("1")) || (ci.SourceItem.Name.StartsWith("2")))
                    {
                        cb.ClipSessionTitle = ci.SourceItem.TimelineYear.ToString();
                    }
                    else
                    {
                        cb.ClipSessionTitle = String.Format("{0} {1}", MonthConvert(ci.SourceItem.TimelineMonth), ci.SourceItem.TimelineYear);
                    }
                    cb.PopulateTiles();
                    cb.PlayClip();
                }
                catch (SystemException se)
                {
                    base.ShowDialog("clipShow exception", se.Message, true);
                }
                return (cb);

            }
        }

        public MediaPlayCodeBehind ResultPageWithChannel
        {
            get
            {
                CleanupThreads();
                MediaPlayCodeBehind cb = new MediaPlayCodeBehind();
                
                if (this.CreatePlaylistMode.Equals(true))
                {
                    int Ctr = 0;
                    foreach (MediaMetaData med in _myChosenContentItems.Options)
                    {
                        if (Ctr == 0)
                        {
                            MediaListItem mli = new MediaListItem();
                            mli.SourceItem = med;
                            mli.SourceItem.Thumbnail = new Image(BuildImagePath(mli.SourceItem.ThumbnailUrl));
                            cb.VideoMetaDataList.Add(mli);
                            Ctr = 1;
                        }
                        else
                        {
                            cb.TileItems.Add(med);
                        }
                    }
                    ClipCollection mc = new ClipCollection();
                    mc.ClipLength = base.AppSettings.DefaultClipLength;
                    mc.Name = "playlist";
                    cb.CurrentChannel = mc;
                    cb.ClipSessionTitle = "Custom Playlist";
                    cb.PopulateTiles();
                    cb.PlayClip();
                    return(cb);
               }

               if (this.CurrentView.Equals(TileViewType.SingleMediaItem))
                {
                    if (this.LinkedPlaylistMode.Equals(true))
                    {
                        int Ctr = 0;
                        foreach (MediaMetaData med in _myChosenContentItems.Options)
                        {
                            if (Ctr == 0)
                            {
                                MediaListItem mli = new MediaListItem();
                                mli.SourceItem = med;
                                mli.SourceItem.Thumbnail = new Image (BuildImagePath(mli.SourceItem.ThumbnailUrl));
                                cb.VideoMetaDataList.Add(mli);
                                Ctr = 1;
                            }
                            else
                            {
                                cb.TileItems.Add(med);
                            }
                        }
                        ClipCollection mc = new ClipCollection();
                        cb.CurrentChannel = mc;
                        cb.ClipSessionTitle = "Linked";
                        cb.PopulateTiles();
                        cb.PlayClip();
                    }
                    else
                    {
                        MediaListItem mli = (MediaListItem)this.VideoMetaDataList[this.CurrentTileIndex];
                        this.VideoMetaDataList.Clear();
                        if (!BuildVideoChildren(mli.MmdSourceItem, true, true))
                        {
                            cb.TileItems.Add(mli.MmdSourceItem);
                        }
                        else
                        {
                            int Ctr = 0;
                            foreach (MediaListItem mli2 in this.VideoMetaDataList)
                            {
                                if (Ctr == 0)
                                {
                                    mli2.SourceItem.Thumbnail = new Image(BuildImagePath(mli.SourceItem.ThumbnailUrl));
                                    cb.VideoMetaDataList.Add(mli2);
                                    Ctr = 1;
                                }
                                else
                                {
                                    cb.TileItems.Add(mli2.SourceItem);
                                }
                            }
                            cb.ClipSessionTitle = String.Format("Linked media to '{0}'", mli.MmdSourceItem.Title);
                        }
                        ClipCollection mc = new ClipCollection();
                        mc.ClipLength = MediaClipLengths.All;
                        cb.CurrentChannel = mc;
                        cb.PopulateTiles();
                        cb.PlayClip();
                    }
                }
                #region Playlist items
                else if (base.CurrentView.Equals(TileViewType.PlayLists))
                {
                    PreviewChannelVItem playList = (PreviewChannelVItem)base.PlaylistMediaLibraryList[base.CurrentTileIndex];
                    Storage st = new Storage();
                    ClipCollection mc = st.GetClipCollection(playList.SourceItem.MediaChannelUri);
                    ClipItem ci2 = (ClipItem)mc.Items[0];
                    int Ctr = 0;
                    foreach (MediaMetaData med in ci2.MediaItems)
                    {
                        if (Ctr == 0)
                        {
                            MediaListItem mli = new MediaListItem(med);
                            mli.SourceItem.Thumbnail = new Image(BuildImagePath(mli.SourceItem.ThumbnailUrl));
                            cb.VideoMetaDataList.Add(mli);
                            Ctr = 0;
                        }
                        else
                        {
                            cb.TileItems.Add(med);
                        }
                    }
                    cb.CurrentChannel = mc;
                    cb.ClipSessionTitle = playList.SourceItem.Name;
                    cb.PopulateTiles();
                    cb.PlayClip();
                }
                #endregion
                #region Snagged items
                else if (base.CurrentView.Equals(TileViewType.Snags))
                {
                    PreviewChannelVItem snagItem = (PreviewChannelVItem)base.SnagMediaLibraryList[base.CurrentTileIndex];
                    ClipCollection mc = new ClipCollection();
                    mc.ClipLength = base.AppSettings.DefaultClipLength;
                    mc.Name = snagItem.SourceItem.Name;
                    mc.Items.Add(snagItem);
                    if (snagItem.SourceItem.Name.Equals("All snags"))
                    {
                        cb.VideoMetaDataList = CoreUICodeBehind.AddItems(MediaPlayCodeBehind.BuildChannelAllSnags());
                    }
                    else 
                    {
                        MediaMetaData parent = (MediaMetaData)snagItem.SourceItem.MediaItems[0];
                        cb.VideoMetaDataList = CoreUICodeBehind.AddItems(MediaPlayCodeBehind.BuildChannelFromSnags(parent));
                    }
                    cb.CurrentChannel = mc;
                    cb.ClipSessionTitle = snagItem.SourceItem.Name;
                    cb.PlayClip();
                }
                #endregion

                return (cb);
            }
        }

        public bool TagsExist
        {
            get
            {
                long maxItems = 0;
                // First get the maxitems in all the media
                foreach (ClipShowContent cm in this.MediaLibraries.Options)
                {
                    if (!cm.ContentSourceName.Equals("my playlists"))
                    {
                        foreach (ClipItem ci in cm.KeywordItems)
                        {
                            if (!ci.Keywords.Equals("ALL"))
                            {
                                maxItems += ci.Count;
                            }
                        }
                    }
                }

                return (maxItems > 0);
            }
        }
        #endregion

        #region Properties
        public bool FinishedCrawling
        {
            get { return (_finishedCrawl); }
        }
        public bool LinkedPlaylistMode
        {
            get { return (_linkedPlaylistMode); }
            set { _linkedPlaylistMode = value; }
        }
        public bool ShowVideoSource
        {
            get { return (_showVideoSources); }
        }
        public Choice ChosenMediaItems
        {
            get { return (_myChosenContentItems); }
        }
        public MediaPlayCodeBehind ResultPageWithChannelFromTag
        {
            get
            {
                CleanupThreads();
                PreviewChannelVItem pci = (PreviewChannelVItem)base.TagMediaLibraryList[base.CurrentTileIndex];
                ClipCollection mc = new ClipCollection();
                mc.ClipLength = base.AppSettings.DefaultClipLength;
                mc.Name = pci.SourceItem.Name;
                mc.Items.Add(pci.SourceItem);

                MediaPlayCodeBehind cb = new MediaPlayCodeBehind();
                cb.VideoMetaDataList = CoreUICodeBehind.AddItems(MediaPlayCodeBehind.BuildChannelFromAll(pci.SourceItem, base.MediaLibraries));
                cb.CurrentChannel = mc;
                cb.ClipSessionTitle = pci.SourceItem.Name;
                cb.PlayClip();
                return (cb);
            }
        }

        public Image FlipThumb
        {
            get
            {
                _thumbFlipIndex++;
                if (_thumbFlipIndex == _thumbFlips.Count)
                {
                    _thumbFlipIndex = 1;
                }
                try
                {
                    string thumbUrl = BuildImagePath((string)_thumbFlips[_thumbFlipIndex]);
                    if(thumbUrl.StartsWith("resx"))
                    {
                        return((Image)_thumbFlips[0]);
                    }
                    else
                    {
                        Image im = new Image(thumbUrl);
                        return (im);
                    }
                }
                catch
                {
                    return ((Image)_thumbFlips[0]);
                }
            }
        }
        public static string AboutText
        {
            get
            {
                StringBuilder result = new StringBuilder();
                result.AppendFormat("clipShow version 1.1.1223");
                return (result.ToString());
            }
        }
        #endregion

        #region Playlist Builder methods
        public void ClearList()
        {
            try
            {
                _myChosenContentItems.Options.Clear();

                ArrayListDataSet temp = new ArrayListDataSet();
                MediaMetaData md = new MediaMetaData();
                md.Thumbnail = new Image("resx://ClipShow/ClipShow.Resources/clipShow_glyph");
                temp.Add(md);
                _myChosenContentItems.Options = temp;
                _firstItemIn = true;
            }
            catch (SystemException se)
            {
                System.Diagnostics.EventLog.WriteEntry("clipShow.ClearList", se.Message);
            }
        }
        public void InitializeList()
        {
            this.CreatePlaylistMode = true;
            _changedPlaylist = new Command();
            FillPlaceholder(new Image("resx://ClipShow/ClipShow.Resources/clipShow_glyph"));
        }
        public Command ChangedPlaylist
        {
            get { return (_changedPlaylist); }
        }
        public bool VideosAdded
        {
            get
            {
                return (!_firstItemIn);
            }
        }
        public ChannelTextBox ResultPageToSave
        {
            get
            {
                CleanupThreads();
                ClipCollection mc = new ClipCollection();
                mc.ClipLength = MediaClipLengths.Long;
                mc.Name = "Clip Name";

                ClipItem ci = new ClipItem();
                ci.Keywords = "ALL";
                ci.Name = "my playlists";

                MediaMetaData tempMd = (MediaMetaData)this._myChosenContentItems.Options[0];
                ci.ThumbnailUrl = tempMd.ThumbnailUrl;
                ci.Count = this._myChosenContentItems.Options.Count;

                foreach (MediaMetaData md in this._myChosenContentItems.Options)
                {
                    ci.MediaItems.Add(md);
                }

                mc.Items.Add(ci);

                ChannelTextBox result = new ChannelTextBox();
                result.SourceChannel = mc;
                result.ChannelItems = this._myChosenContentItems;

                return (result);
            }
        }

        private void CleanupThreads()
        {
            try
            {
                // First stop the thumbnail thread if it is running
                if (_thread.IsAlive)
                {
                    _thread.Abort();
                }
            }
            catch { }
        }
        public void FillPlaceholder(Image placeholder)
        {
            if (_myChosenContentItems.Options == null)
            {
                // Create place holder for selection items
                ArrayListDataSet temp = new ArrayListDataSet();
                MediaMetaData md = new MediaMetaData();
                md.Thumbnail = placeholder;
                temp.Add(md);
                _myChosenContentItems.Options = temp;
            }
        }

        public void AddAllMedia()
        {
            ArrayListDataSet temp = new ArrayListDataSet();
            foreach (MediaListItem item in base.VideoMetaDataList)
            {
                temp.Add(item.SourceItem);
            }

            _myChosenContentItems.Options = temp;
        }

        public void AddMediaListItem(MediaListItem itemToAdd)
        {
            _myChosenContentItems.Options.Add(itemToAdd.SourceItem);
            if (_firstItemIn)
            {
                _firstItemIn = false;
                _myChosenContentItems.Options.RemoveAt(0);
            }
        }

        public void AddClipItem(ClipItem itemToAdd)
        {
            if (base.CurrentView.Equals(TileViewType.Topics))
            {
                string keyWords = itemToAdd.Keywords;
                foreach (ClipShowContent lib in base.MediaLibraries.Options)
                {
                    foreach (MediaMetaData item in lib.MediaItems)
                    {
                        if (!item.Title.Equals("N/A"))
                        {
                            if (keyWords.Equals("ALL"))
                            {
                                item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
                                _myChosenContentItems.Options.Add(item);
                            }
                            else
                            {
                                string[] keywords = keyWords.Split(';');
                                foreach (string keyword in keywords)
                                {
                                    if (CheckForKeyword(item, keyword))
                                    {
                                        if (!_myChosenContentItems.Options.Contains(item))
                                        {
                                            item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
                                            _myChosenContentItems.Options.Add(item);
                                        }
                                        break;
                                    }
                                }
                            }

                        }
                    }
                }
            }
            if (base.CurrentView.Equals(TileViewType.Timeline))
            {
                foreach (MediaMetaData item in itemToAdd.MediaItems)
                {
                    item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
                    _myChosenContentItems.Options.Add(item);
                }
            }
            else if (base.CurrentView.Equals(TileViewType.PlayLists))
            {
                Storage st = new Storage();
                ClipCollection mc = st.GetClipCollection(itemToAdd.MediaChannelUri);
                ClipItem ci2 = (ClipItem)mc.Items[0];
                foreach (MediaMetaData med in ci2.MediaItems)
                {
                    med.Thumbnail = new Image(BuildImagePath(med.ThumbnailUrl));
                    _myChosenContentItems.Options.Add(med);
                }
            }
            else if (base.CurrentView.Equals(TileViewType.Snags))
            {
                if (itemToAdd.Name.Equals("All snags"))
                {
                    Storage st = new Storage();
                    ClipShowContent csc = st.GetSnagCollection();
                    foreach (MediaMetaData clip in csc.MediaItems)
                    {
                        foreach (SnagItem si in clip.SnagList)
                        {
                            MediaMetaData item = clip.Clone();
                            item.Title = String.Format("{0} ({1})", clip.Title, si.SnagName);
                            if (File.Exists(si.ThumbnailUrl))
                            {
                                item.Thumbnail = new Image(BuildImagePath(si.ThumbnailUrl));
                            }
                            else
                            {
                                item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
                            }
                            item.SnagClipLength = si.ClipLength;
                            item.SnagTimeSpan = si.ItemTimeSpan.ToString(); // si.StartTime;
                            item.IsSnagItem = true;
                            _myChosenContentItems.Options.Add(item);
                        }
                    }

                }
                else
                {
                    MediaMetaData parent = (MediaMetaData)itemToAdd.MediaItems[0];
                    string parentTitle = parent.Title;
                    foreach (SnagItem si in parent.SnagList)
                    {
                        MediaMetaData item = parent.Clone();
                        item.Title = String.Format("{0} ({1})", parentTitle, si.SnagName);
                        if (File.Exists(si.ThumbnailUrl))
                        {
                            item.Thumbnail = new Image(BuildImagePath(si.ThumbnailUrl));
                        }
                        else
                        {
                            item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
                        }
                        item.SnagClipLength = si.ClipLength;
                        item.SnagTimeSpan = si.ItemTimeSpan.ToString(); // si.StartTime;
                        item.IsSnagItem = true;
                        _myChosenContentItems.Options.Add(item);
                    }
                }
            }
            //else if(base.CurrentView.Equals(TileViewType.MediaItems))
            //{
            //    if (itemToAdd.Keywords.Equals("ALL"))
            //    {
            //        foreach (ClipShowContent cm in base.MediaLibraries.Options)
            //        {
            //            if (cm.ContentSourceName.Equals(itemToAdd.MediaChannelUri))
            //            {
            //                foreach (MediaMetaData med in cm.MediaItems)
            //                {
            //                    med.Thumbnail = new Image(BuildImagePath(med.ThumbnailUrl));
            //                    _myChosenContentItems.Options.Add(med);
            //                }
            //                break;
            //            }
            //        }
            //    }
            //    else
            //    {
            //        string keyWords = itemToAdd.Keywords;
            //        foreach (ClipShowContent lib in base.MediaLibraries.Options)
            //        {
            //            foreach (MediaMetaData item in lib.MediaItems)
            //            {
            //                if (!item.Title.Equals("N/A"))
            //                {
            //                    if (keyWords.Equals("ALL"))
            //                    {
            //                        item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
            //                        _myChosenContentItems.Options.Add(item);
            //                    }
            //                    else
            //                    {
            //                        string[] keywords = keyWords.Split(';');
            //                        foreach (string keyword in keywords)
            //                        {
            //                            if (CheckForKeyword(item, keyword))
            //                            {
            //                                if (!_myChosenContentItems.Options.Contains(item))
            //                                {
            //                                    item.Thumbnail = new Image(BuildImagePath(item.ThumbnailUrl));
            //                                    _myChosenContentItems.Options.Add(item);
            //                                }
            //                                break;
            //                            }
            //                        }
            //                    }

            //                }
            //            }
            //        }
            //    }
            //}
            if (_firstItemIn)
            {
                _firstItemIn = false;
                _myChosenContentItems.Options.RemoveAt(0);
            }

            _playListMessage = String.Format("Playlist ({0})", _myChosenContentItems.Options.Count);
            _changedPlaylist.Invoke();
        }

        public void RemoveMediaItem(int mediaIndex)
        {
            if (!_firstItemIn)
            {
                _myChosenContentItems.Options.RemoveAt(mediaIndex);
            }
            
            // Show placeholder if empty list
            if (_myChosenContentItems.Options.Count.Equals(0))
            {
                ArrayListDataSet temp = new ArrayListDataSet();
                MediaMetaData md = new MediaMetaData();
                md.Thumbnail = new Image("resx://ClipShow/ClipShow.Resources/clipShow_glyph");
                temp.Add(md);
                _myChosenContentItems.Options = temp;
                _firstItemIn = true;
            }
        }

        string _playListMessage = "Playlist (0 items)";
        public string PlaylistMessage
        {
            get { return (_playListMessage); }
            set { _playListMessage = value; }
        }
        #endregion

        public void BuildThumbList(PreviewChannelVItem item)
        {
            _thumbFlips.Clear();

            // Add current preview item thumb nail first
            _thumbFlips.Add(item.SourceItem.Thumbnail);
            _thumbFlipIndex = 1;

            if (this.CurrentView.Equals(TileViewType.Snags))
            {
                Storage st = new Storage();
                ClipShowContent cm = st.GetSnagCollection();
                if (item.SourceItem.Keywords.Equals("ALL"))
                {
                    foreach (MediaMetaData ci in cm.MediaItems)
                    {
                        foreach (SnagItem si in ci.SnagList)
                        {
                            _thumbFlips.Add(si.ThumbnailUrl);
                        }
                    }
                }
                else
                {
                    foreach (MediaMetaData ci in cm.MediaItems)
                    {
                        if (item.SourceItem.Name.Equals(ci.Title))
                        {
                            _thumbFlips.Add(ci.ThumbnailUrl);
                            foreach (SnagItem si in ci.SnagList)
                            {
                                _thumbFlips.Add(si.ThumbnailUrl);
                            }
                            break;
                        }
                    }
                }
            }

            if (this.CurrentView.Equals(TileViewType.PlayLists))
            {
                Storage st = new Storage();
                foreach (ClipCollection mc in st.GetMyCollections())
                {
                    if (mc.Name.Equals(item.SourceItem.Name))
                    {
                        ClipItem ci = (ClipItem)mc.Items[0];
                        foreach (MediaMetaData med in ci.MediaItems)
                        {
                            _thumbFlips.Add(med.ThumbnailUrl);
                        }
                        break;
                    }
                }
            }

            if (this.CurrentView.Equals(TileViewType.Timeline))
            {
                foreach (MediaMetaData s in item.SourceItem.MediaItems)
                {
                    _thumbFlips.Add(s.ThumbnailUrl);
                }
            }

            //if (this.CurrentView.Equals(TileViewType.MediaItems))
            //{
            //    string keyWords = item.SourceItem.Keywords;
            //    foreach (ClipShowContent mc2 in base.MediaLibraries.Options)
            //    {
            //        foreach (MediaMetaData s in mc2.MediaItems)
            //        {
            //            if (!s.Title.Equals("N/A"))
            //            {
            //                if (keyWords.Equals("ALL"))
            //                {
            //                    _thumbFlips.Add(s.ThumbnailUrl);
            //                }
            //                else
            //                {
            //                    string[] keywords = keyWords.Split(';');
            //                    foreach (string keyword in keywords)
            //                    {
            //                        if (CheckForKeyword(s, keyword))
            //                        {
            //                            if (!_thumbFlips.Contains(s.ThumbnailUrl))
            //                            {
            //                                _thumbFlips.Add(s.ThumbnailUrl);
            //                            }
            //                            break;
            //                        }
            //                    }
            //                }

            //            }
            //        }
            //    }
            //}
        }
    }
}
